package com.reverie.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.reverie.common.pojo.CommonPageReq;
import com.reverie.common.pojo.CommonResult;
import com.reverie.dto.req.GoodQueryParam;
import com.reverie.dto.req.GoodSaleStatusParam;
import com.reverie.entity.Goods;
import com.reverie.service.ICartService;
import com.reverie.service.IGoodsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author Rui.Zhou
 * @since 2024-02-03
 */
@RestController
@RequestMapping("/good")
public class GoodsController {
    @Autowired
    private IGoodsService goodsService;
    @Autowired
    private ICartService cartService;

    @PostMapping("save")
    public CommonResult<Boolean> onSave(@RequestBody Goods goods) {
        return CommonResult.data(goodsService.onSave(goods));
    }

    @PostMapping("queryPage")
    public CommonResult<Page<Goods>> queryPage(@RequestBody CommonPageReq<GoodQueryParam> queryParam) {
        return CommonResult.data(goodsService.queryPage(queryParam));
    }

    @PostMapping("switchSale")
    @Transactional(rollbackFor = Exception.class)
    public CommonResult<Boolean> switchSale(@RequestBody GoodSaleStatusParam goodSaleStatusParam) {
        Goods goods = goodsService.getById(goodSaleStatusParam.getGoodsId());
        goods.setIsOnSale(goodSaleStatusParam.getIsOnSale());
        boolean saved = goodsService.updateById(goods);
        if(saved && !goodSaleStatusParam.getIsOnSale()){
            cartService.removeByGoodsId(goodSaleStatusParam.getGoodsId());
        }
        return CommonResult.data(saved);
    }

    @PostMapping("delete")
    public CommonResult<Boolean> delete(@RequestBody Goods goods) {
        return CommonResult.data(goodsService.removeById(goods.getGoodsId()));
    }
}
